<template>
  <div class="forgot-password-container">
    <!-- 背景装饰 -->
    <div class="bg-decoration">
      <div class="floating-shape shape-1"></div>
      <div class="floating-shape shape-2"></div>
      <div class="floating-shape shape-3"></div>
    </div>
    
    <div class="forgot-password-wrapper">
      <!-- 左侧信息面板 -->
      <div class="info-panel">
        <div class="logo-section">
          <div class="logo-icon">
            <i class="el-icon-key"></i>
          </div>
          <h1 class="system-title">找回密码</h1>
          <p class="system-subtitle">通过邮箱验证重置您的密码</p>
        </div>
        <div class="feature-list">
          <div class="feature-item">
            <i class="el-icon-message"></i>
            <span>邮箱验证安全</span>
          </div>
          <div class="feature-item">
            <i class="el-icon-lock"></i>
            <span>密码加密保护</span>
          </div>
          <div class="feature-item">
            <i class="el-icon-time"></i>
            <span>快速重置流程</span>
          </div>
        </div>
      </div>
      
      <!-- 右侧表单面板 -->
      <div class="form-panel">
        <el-card class="forgot-password-card">
          <div class="card-header">
            <h2>重置密码</h2>
            <p>请填写您的账户信息</p>
          </div>
          
          <el-form 
            :model="forgotPasswordForm" 
            :rules="forgotPasswordRules" 
            ref="forgotPasswordFormRef" 
            class="forgot-password-form"
            @keyup.enter="handleForgotPassword"
          >
            <el-form-item prop="username">
              <el-input
                v-model="forgotPasswordForm.username"
                placeholder="请输入用户名"
                size="large"
                clearable
              >
                <template #prefix>
                  <el-icon><User /></el-icon>
                </template>
              </el-input>
            </el-form-item>
            
            <el-form-item prop="email">
              <el-input
                v-model="forgotPasswordForm.email"
                placeholder="请输入邮箱地址"
                size="large"
                clearable
              >
                <template #prefix>
                  <el-icon><Message /></el-icon>
                </template>
              </el-input>
            </el-form-item>
            
            <el-form-item prop="newPassword">
              <el-input
                v-model="forgotPasswordForm.newPassword"
                type="password"
                placeholder="请输入新密码"
                size="large"
                show-password
                clearable
              >
                <template #prefix>
                  <el-icon><Lock /></el-icon>
                </template>
              </el-input>
            </el-form-item>
            
            <el-form-item prop="verificationCode">
              <div class="verification-input">
                <el-input
                  v-model="forgotPasswordForm.verificationCode"
                  placeholder="请输入验证码"
                  size="large"
                  clearable
                >
                  <template #prefix>
                    <el-icon><Key /></el-icon>
                  </template>
                </el-input>
                <el-button 
                  type="primary" 
                  size="large"
                  :disabled="countdown > 0 || sendingCode"
                  @click="sendVerificationCode"
                  class="send-code-btn"
                >
                  {{ countdown > 0 ? `${countdown}s` : (sendingCode ? '发送中...' : '发送验证码') }}
                </el-button>
              </div>
            </el-form-item>
            
            <el-form-item>
              <el-button 
                type="primary" 
                size="large" 
                @click="handleForgotPassword"
                :loading="loading"
                class="submit-btn"
                block
              >
                {{ loading ? '重置中...' : '重置密码' }}
              </el-button>
            </el-form-item>
            
            <div class="auth-links">
              <el-button type="text" @click="goToLogin" class="link-btn">
                <i class="el-icon-back"></i>
                返回登录
              </el-button>
              <el-button type="text" @click="goToRegister" class="link-btn">
                <i class="el-icon-user-solid"></i>
                还没有账号？立即注册
              </el-button>
            </div>
          </el-form>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted, onUnmounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import type { FormInstance, FormRules } from 'element-plus';
import { User, Message, Lock, Key } from '@element-plus/icons-vue';
import { sendForgotPasswordCode, resetPasswordByCode } from '../api/auth';

const router = useRouter();
const forgotPasswordFormRef = ref<FormInstance>();
const loading = ref(false);
const sendingCode = ref(false);
const countdown = ref(0);
let countdownTimer: NodeJS.Timeout | null = null;

const forgotPasswordForm = reactive({
  username: '',
  email: '',
  newPassword: '',
  verificationCode: '',
});

const forgotPasswordRules = reactive<FormRules>({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 15, message: '用户名长度在 3 到 15 个字符', trigger: 'blur' },
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' },
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 18, message: '密码长度在 6 到 18 个字符', trigger: 'blur' },
  ],
  verificationCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { len: 6, message: '验证码为6位数字', trigger: 'blur' },
  ],
});

// 发送验证码
const sendVerificationCode = async () => {
  if (!forgotPasswordForm.username || !forgotPasswordForm.email) {
    ElMessage.warning('请先填写用户名和邮箱');
    return;
  }
  
  sendingCode.value = true;
  try {
    await sendForgotPasswordCode({
      username: forgotPasswordForm.username,
      email: forgotPasswordForm.email,
    });
    
    ElMessage.success('验证码已发送到您的邮箱');
    startCountdown();
  } catch (error: any) {
    console.error('发送验证码失败:', error);
    ElMessage.error(error.response?.data?.message || '发送验证码失败');
  } finally {
    sendingCode.value = false;
  }
};

// 开始倒计时
const startCountdown = () => {
  countdown.value = 60;
  countdownTimer = setInterval(() => {
    countdown.value--;
    if (countdown.value <= 0) {
      clearInterval(countdownTimer!);
      countdownTimer = null;
    }
  }, 1000);
};

// 重置密码
const handleForgotPassword = () => {
  if (!forgotPasswordFormRef.value) return;
  
  forgotPasswordFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true;
      try {
        await resetPasswordByCode({
          username: forgotPasswordForm.username,
          email: forgotPasswordForm.email,
          newPassword: forgotPasswordForm.newPassword,
          verificationCode: forgotPasswordForm.verificationCode,
        });
        
        ElMessage.success({
          message: '密码重置成功，请使用新密码登录',
          type: 'success',
          duration: 3000
        });
        
        // 延迟跳转到登录页面
        setTimeout(() => {
          router.push('/login');
        }, 1500);
        
      } catch (error: any) {
        console.error('重置密码失败:', error);
        ElMessage.error(error.response?.data?.message || '重置密码失败');
      } finally {
        loading.value = false;
      }
    } else {
      ElMessage.warning('请填写完整且正确的信息');
    }
  });
};

// 跳转到登录页面
const goToLogin = () => {
  router.push('/login');
};

// 跳转到注册页面
const goToRegister = () => {
  router.push('/register');
};

// 检查登录状态
onMounted(() => {
  const isLoggedIn = localStorage.getItem('loggedIn');
  if (isLoggedIn === 'true') {
    router.push('/study-system');
  }
});

// 清理定时器
onUnmounted(() => {
  if (countdownTimer) {
    clearInterval(countdownTimer);
  }
});
</script>

<style scoped>
.forgot-password-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  overflow: hidden;
}

.bg-decoration {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  pointer-events: none;
}

.floating-shape {
  position: absolute;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.1);
  animation: float 6s ease-in-out infinite;
}

.shape-1 {
  width: 80px;
  height: 80px;
  top: 20%;
  left: 10%;
  animation-delay: 0s;
}

.shape-2 {
  width: 120px;
  height: 120px;
  top: 60%;
  right: 15%;
  animation-delay: 2s;
}

.shape-3 {
  width: 60px;
  height: 60px;
  bottom: 20%;
  left: 20%;
  animation-delay: 4s;
}

@keyframes float {
  0%, 100% {
    transform: translateY(0px) rotate(0deg);
  }
  50% {
    transform: translateY(-20px) rotate(180deg);
  }
}

.forgot-password-wrapper {
  display: flex;
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
  padding: 40px;
  gap: 60px;
  align-items: center;
}

.info-panel {
  flex: 1;
  color: white;
  padding: 40px;
}

.logo-section {
  margin-bottom: 60px;
}

.logo-icon {
  width: 80px;
  height: 80px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 30px;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.3);
}

.logo-icon i {
  font-size: 36px;
  color: white;
}

.system-title {
  font-size: 48px;
  font-weight: 700;
  margin: 0 0 16px 0;
  background: linear-gradient(45deg, #fff, #f0f0f0);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.system-subtitle {
  font-size: 18px;
  opacity: 0.9;
  margin: 0;
  line-height: 1.6;
}

.feature-list {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.feature-item {
  display: flex;
  align-items: center;
  gap: 16px;
  font-size: 16px;
  opacity: 0.9;
}

.feature-item i {
  font-size: 20px;
  width: 24px;
  text-align: center;
}

.form-panel {
  flex: 1;
  max-width: 480px;
}

.forgot-password-card {
  border-radius: 24px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.1);
  border: none;
  overflow: hidden;
  backdrop-filter: blur(20px);
  background: rgba(255, 255, 255, 0.95);
}

.card-header {
  text-align: center;
  margin-bottom: 32px;
  padding: 32px 32px 0;
}

.card-header h2 {
  font-size: 28px;
  font-weight: 600;
  color: #2c3e50;
  margin: 0 0 8px 0;
}

.card-header p {
  color: #7f8c8d;
  margin: 0;
  font-size: 14px;
}

.forgot-password-form {
  width: 100%;
  max-width: 350px;
  margin: 0 auto;
}

:deep(.el-form-item__label) {
  font-size: 14px;
  color: #333;
  margin-bottom: 8px;
}

:deep(.el-form-item) {
  margin-bottom: 20px;
}

.password-tip {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
  text-align: left;
}

.verification-code-wrapper {
  display: flex;
  gap: 10px;
}

.verification-code-input {
  flex-grow: 1;
}

.send-code-btn {
  width: 120px;
}

.submit-btn {
  width: 100%;
  height: 40px;
  margin-top: 10px;
}

.auth-links {
  display: flex;
  justify-content: space-between;
  margin-top: 24px;
  padding-top: 24px;
  border-top: 1px solid #eee;
}

.link-btn {
  color: #409eff;
  font-size: 14px;
  padding: 0;
  height: auto;
}

.link-btn:hover {
  color: #66b1ff;
}

.link-btn i {
  margin-right: 4px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .forgot-password-wrapper {
    flex-direction: column;
    padding: 20px;
    gap: 30px;
  }
  
  .info-panel {
    text-align: center;
    padding: 20px;
  }
  
  .system-title {
    font-size: 36px;
  }
  
  .form-panel {
    width: 100%;
    max-width: 400px;
  }
  
  .verification-input {
    flex-direction: column;
  }
  
  .send-code-btn {
    width: 100%;
  }
  
  .auth-links {
    flex-direction: column;
    gap: 12px;
    text-align: center;
  }
}
</style>